package com.tledu.springbootmybatis.core.interceptor;

import com.tledu.springbootmybatis.core.constants.CommonConstants;
import com.tledu.springbootmybatis.domain.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author cyrus
 */
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // true代表如果没有session就会创建一个session，false没有session就会返回null
        HttpSession session = request.getSession(true);
        User user = (User) session.getAttribute(CommonConstants.LOGIN_USER_SESSION_KEY);
        if (user == null) {
            // 代表没有登录
            response.sendRedirect(request.getContextPath() + "/login");
            // 终止后续请求
            return false;
        }
        return true;
    }
}
